package com.lefevre.cms.web.action.user;


import com.lefevre.cms.bean.*;
import com.lefevre.cms.bean.user.User;
import com.lefevre.cms.bean.user.UserLoginLog;
import com.lefevre.cms.service.setting.SettingService;
import com.lefevre.cms.service.user.UserService;
import com.lefevre.cms.utils.IpAddress;
import com.lefevre.cms.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录日志
 */
@Controller
public class UserLoginLogAction {

    @Resource
    UserService userService;
    @Resource
    SettingService settingService;

    /**
     * 用户登录日志列表
     *
     * @param userId   用户Id
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/control/userLoginLog/list")
    public String execute(ModelMap model, Long id, PageForm pageForm,
                          HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        Map<String, String> error = new HashMap<>();
        Map<String, Object> returnValue = new HashMap<>();


        if (id != null && id > 0L) {
            //调用分页算法代码
            PageView<UserLoginLog> pageView = new PageView<UserLoginLog>(settingService.findSystemSetting_cache().getBackstagePageNumber(), pageForm.getPage(), 10);
            //当前页
            int firstIndex = (pageForm.getPage() - 1) * pageView.getMaxresult();
            ;
            QueryResult<UserLoginLog> qr = userService.findUserLoginLogPage(id, firstIndex, pageView.getMaxresult());

            if (qr != null && qr.getResultlist() != null && qr.getResultlist().size() > 0) {
                for (UserLoginLog userLoginLog : qr.getResultlist()) {
                    if (userLoginLog.getIp() != null && !"".equals(userLoginLog.getIp().trim())) {
                        userLoginLog.setIpAddress(IpAddress.queryAddress(userLoginLog.getIp()));
                    }
                }
            }

            //将查询结果集传给分页List
            pageView.setQueryResult(qr);
            User _user = userService.findUserById(id);
            if (_user != null) {
                returnValue.put("currentUser", _user);
            }
            returnValue.put("pageView", pageView);
        } else {
            error.put("userId", "用户Id不能为空");
        }
        if (error.size() > 0) {
            return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
        } else {
            return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, returnValue));
        }
    }
}
